#!usr/bin/env python3
from xml.parsers.expat import ParserCreate
from collections import namedtuple
import os
#获取当前路径
ROOT_PATH = os.path.split(__file__)[0]
print('当前工作目录:',ROOT_PATH)

class XmlElement(object):
    def __init__(self,attr,char,name="",parent=None):        
        self.attr = attr
        self.char = char
        self.name = name
        self.parent = parent

#解释xml的类
class DFSaxXmlParser(object):	
	def __init__(self,xml):
		self._xmlData = dict();
		self._xml = xml
		self._curNode=''        
		self._curIndex = -1;		
		self.parse(self._xml);
		
	def parse(self,xml):
		p = ParserCreate()
		p.StartElementHandler = self.start_element
		p.EndElementHandler = self.end_element
		p.CharacterDataHandler = self.char_data
		p.Parse(xml)
		
	def getCurNodes(self):
		if self._curNode in self._xmlData:
			curNodes = self._xmlData[self._curNode]
		else:
			curNodes = [];
			self._xmlData[self._curNode] = curNodes;		
		return curNodes
	
	def start_element(self,name,attrs):
		print("start_element:",(name,attrs,type(attrs)))	
		if self._curNode!=name:
			split= "." if self._curNode!="" else "";
			#self._curNode = self._curNode+split+name;
			self._curNode = name
			self._curIndex = 0;
		
		curNodes = self.getCurNodes()
		line = XmlElement(attrs,'')
		curNodes.append(line)
		self._curLine = line
		
	def char_data(self,text):
		print("char_data:",("字符为空" if text=="" else text),self._curIndex,self._curNode)		
		if self._curLine:
			self._curLine.char=self._curLine.char+text
			print("char_data: self._curLine.char=",self._curLine.char,self._curLine.attr)
		
	def end_element(self,name):
		print("end_element:",name)
	@property
	def xmlData(self):
		if not hasattr(self,"_xmlData"):
			self._xmlData = dict();
		return self._xmlData

xmlUrl = os.path.join(ROOT_PATH,'5.xml')	
#f = open(xmlUrl,'r',encoding='utf-8') #读取文件
f = open(xmlUrl,'rb') #读取文件
xmlStr = f.read();
xmlStr = xmlStr.decode(encoding='utf-8')

dfSax = DFSaxXmlParser(xmlStr)

items = dfSax.xmlData['Protos']
print(type(items))
print(len(items))
print(items[0].__dict__)
exit()
for i,v in enumerate(items):	
	print("char len=",len(items[i].char),'attr=',items[i].attr,'char=',items[i].char)
    
    

    
    
    